//
//  ComposeViewController.swift
//  波波微博
//
//  Created by wave on 15/8/5.
//  Copyright © 2015年 wave. All rights reserved.
//

import UIKit
import SVProgressHUD

//定义一个可发送微博的长度
private let kTextNumberMaxLength = 10

class ComposeViewController: UIViewController,UITextViewDelegate {
    
    //照片选择控制器
    private lazy var photoChooseVC: photoSelectorVC = photoSelectorVC()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //注册分享新鲜事的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "ClearTempLabel", name: UITextViewTextDidChangeNotification, object: nil)
        
        //注册rightItem的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "rightButton", name: UITextViewTextDidChangeNotification, object: nil)
        //上来直接让发布按钮禁用
        navigationItem.rightBarButtonItem?.enabled = false
        
        addKeyboardOberserver()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        //激活键盘
        textView.becomeFirstResponder()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    //搭建界面
    override func loadView() {
        view = UIView()
        //若发现切换控制器的时候会有卡顿现象或者闪烁,重点检查是否设置了背景颜色!!
        //        view.backgroundColor = UIColor.whiteColor()
        view.addSubview(textView)
        view.addSubview(photoChooseVC.view)
        view.addSubview(toolbar)
        
        
        addChildViewController(photoChooseVC)
        
        setupUI()
        prepareToolbar()
        prepareTextView()
        preparePhotoView()
    }
    
    
    //添加键盘通知
    private func addKeyboardOberserver(){
    
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    //删除键盘通知
    private func removieKetboardOberserver(){
    
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    deinit{
        removieKetboardOberserver()
    }
    
    //toolbar底部约束
    private var toolbarBottomCons: NSLayoutConstraint?
    
    //添加键盘注册通知监听的方法
    func keyboardChanged(n:NSNotification){
    
        //获取目标的frame
        let rect = n.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
        
        //获取动画时长
        let duration = n.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        
        //设置约束
        toolbarBottomCons?.constant = -(UIScreen.mainScreen().bounds.height - rect.origin.y)
            
        //动画
        UIView.animateWithDuration(duration) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    //MARK: - 监听方法
    func close(){
        
        dismissViewControllerAnimated(true, completion: nil)
        textView.removeFromSuperview()
    }
    
    //监听发布按钮
    func sendStatus(){
        
        let text = textView.text
        
        //发布微博之前进行判断
        if textView.text.characters.count > kTextNumberMaxLength{
            
            SVProgressHUD.showInfoWithStatus("您输入的文字过长", maskType: SVProgressHUDMaskType.Gradient)
            
            return
        }
        
        //2. 发布微博
        //获取发布微博的图片,如果用户没有选择,image == nil
        let image = photoChooseVC.photos.last
        NetworkTools.sharedTools.sendStatus(text, image: image) { (result, error) -> () in
            if error != nil{
                SVProgressHUD.showInfoWithStatus("您的网络不给力", maskType: SVProgressHUDMaskType.Gradient)
            }

            self.close()
        }
    }
    
    //监听toolbar的表情按钮
    func inputEmoticon(){
        
        print("选择表情")
    }
    func inputImage(){
        
        print("选择照片")
    }
    
    //通知监听的方法
    func ClearTempLabel()
    {
        placholderLabel.hidden = (textView.text == "") ? false : true
    }
    //通知rightButton监听的方法
    func rightButton()
    {
        navigationItem.rightBarButtonItem?.enabled = (textView.text == "") ? false : true
    }
    
    //MARK: - 布局界面
    private func setupUI(){
        //左边按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")

        //textView的文字提示label
        textView.addSubview(promptLabel)
        promptLabel.text = String(kTextNumberMaxLength)
        promptLabel.textColor = UIColor.redColor()
        promptLabel.ff_AlignInner(type: ff_AlignType.BottomRight, referView: textView, size: nil, offset: CGPoint(x: -8, y: -8))
        
        //标题栏
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 32))
        
        let titleLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 15)
        titleLabel.text = "发微博"
        titleLabel.sizeToFit()
        titleView.addSubview(titleLabel)
        titleLabel.ff_AlignInner(type: ff_AlignType.TopCenter, referView: titleView, size: nil)
        
        let nameLabel = UILabel(color: UIColor.lightGrayColor(), fontSize: 13)
        nameLabel.text = UserAccount.sharedUserAccount?.name ?? ""
        nameLabel.sizeToFit()
        titleView.addSubview(nameLabel)
        nameLabel.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: titleView, size: nil)
        
        navigationItem.titleView = titleView
    }

    //toolbar
    private func prepareToolbar(){
    
        toolbar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
//        view.addSubview(toolbar)   //->这里要注意了,只能添加上去后才可以设置自动布局
        //设置布局
        let cons = toolbar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 44))
        //记录底部约束
        toolbarBottomCons = toolbar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
        
        // 定义一个数组
        let itemSettings = [["imageName": "compose_toolbar_picture","action":"inputImage"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background","action":"inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        var items = [UIBarButtonItem]()
        for dict in itemSettings{
            
            //调用分类的方法就可以一句话封装完成
            items.append(UIBarButtonItem(imageName: dict["imageName"]!, target: self, action: dict["action"]))

            //放置弹簧,将5个控件弹开
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        //最后一个不会靠最右,所以删除最后一个弹簧
        items.removeLast()
        
        //设置pp的items
        toolbar.items = items

    }
    
    //textView: 准备输入文字文本框
    private func prepareTextView(){
    
        textView.backgroundColor = UIColor.whiteColor()
//        textView.backgroundColor = UIColor(patternImage: UIImage(named: "Unknown")!)
        textView.textColor = UIColor.redColor()
//        view.addSubview(textView)

        /*
            自动布局
        提示:在ios开发中,如果是单纯的nav+scrollView会自动调整滚动视图的边距
            会将顶部的导航栏的高度预留出来,就能实现滚动视图穿透效果
        */
        //      该属性是镶嵌从封闭的滚动视图的内容视图的距离。默认是uiedgeinsetszero。
        //设置布局
        textView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: nil)
        textView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolbar, size: nil)
     
        //添加占位标签
        placholderLabel.text = "分享新鲜事....."
        placholderLabel.sizeToFit()
        textView.addSubview(placholderLabel)
        placholderLabel.ff_AlignInner(type: ff_AlignType.TopLeft, referView: textView, size: nil, offset: CGPoint(x: 5, y: 8))
    }
    
    //准备照片选择视图
    private func preparePhotoView(){
        
        //1.添加视图
//        view.addSubview(photoChooseVC.view)
        
        //2. 自动布局
        var s = UIScreen.mainScreen().bounds.size
        s.height = 0.6 * s.height
        
        photoChooseVC.view.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: s)
    }
    
    //MARK: - 懒加载
    //懒加载
    private lazy var textView:UITextView = {
        
        let t = UITextView()
        
        t.font = UIFont.systemFontOfSize(18)
        
        //允许垂直拖拽
        t.alwaysBounceVertical = true
        
        //拖动关闭键盘
        t.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        return t
    }()
    
    //懒加载toolbar
    private lazy var toolbar: UIToolbar = UIToolbar()
    
    //懒加载占位标签
    private lazy var placholderLabel = UILabel(color: UIColor.lightGrayColor(), fontSize: 15)
    
    //懒加载文字提示标签
    private lazy var promptLabel: UILabel = UILabel(color: UIColor.lightGrayColor(), fontSize: 12)
}
